package com.gcloud.configuracion;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.CheckBox;
import android.widget.Toast;
import com.example.gcode.*;
import com.gcloud.dto.GCloudAccount;
import com.gcloud.persistance.SQLiteHandler;
import com.utils.Constants;
import com.utils.Message;

public class Usuario extends ListActivity {
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.usuario_layout);
		listAccounts();
	}

	List<GCloudAccount> accountList = new ArrayList<GCloudAccount>();

	private void listAccounts() {
		SQLiteHandler sqliteHandler = new SQLiteHandler(Usuario.this,
				Constants.GCLOUD, null, Constants.DB_VERSION);
		try {
			accountList = sqliteHandler.getAccountList();
		} catch (SQLException e) {
			Log.e("Usuario: ", "" + e);
			showToast(Message.ERROR_RETRIEVING_ACCOUNT);
		}
		ArrayAdapter<GCloudAccount> accountAdapter = new UserAdapter();
		setListAdapter(accountAdapter);
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	private class UserAdapter extends ArrayAdapter<GCloudAccount> {

		public UserAdapter() {
			super(Usuario.this, R.layout.account_item, accountList);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View viewItem = convertView;
			if (viewItem == null) {
				viewItem = getLayoutInflater().inflate(R.layout.account_item,
						parent, false);
			}
			GCloudAccount currentAccount = accountList.get(position);
			if(currentAccount==null){
				return viewItem;
			}
			ImageView imageAccount = (ImageView) viewItem
					.findViewById(R.id.imageAccountI);
			if(currentAccount.getService()!=null){
			if (currentAccount.getService().equals(Constants.GOOGLE)) {
				imageAccount.setImageResource(R.drawable.googledrive);
			} else {
				imageAccount.setImageResource(R.drawable.dropbox);
			}
			}else{
				imageAccount.setImageResource(R.drawable.googledrive);
			}
			TextView accountName = (TextView) viewItem
					.findViewById(R.id.textAccountName);
			accountName.setText(currentAccount.getAccount());
			CheckBox active = (CheckBox) viewItem
					.findViewById(R.id.checkBoxActiveA);
			active.setChecked(currentAccount.getActive() == 1 ? true : false);			
			return viewItem;
		}

	}

}
